package com.browse.config;

import com.common.exception.CodeAndMsg;
import com.common.exception.JavaSmException;
import com.google.common.collect.Range;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;

/**
 * @author 路亚
 * @version 0.1
 * @className CustomerShardingAlgorithm
 * @description
 * @date 2024/12/28 16:47
 * @since jdk11
 */
public class CustomerShardingAlgorithm implements StandardShardingAlgorithm<LocalDateTime> {

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<LocalDateTime> preciseShardingValue) {
        // 传递的日期值
        LocalDateTime paramValue = preciseShardingValue.getValue();
        String format = paramValue.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        List<String> tables = List.copyOf(collection);
        for (String table : tables) {
            if (table.contains(format)) {
                return table;
            }
        }
        throw new JavaSmException(CodeAndMsg.TABLE_NOT_EXIST);
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<LocalDateTime> rangeShardingValue) {
        Range<LocalDateTime> valueRange = rangeShardingValue.getValueRange();
        LocalDateTime localDateTime = valueRange.upperEndpoint();
        String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        List<String> tables = List.copyOf(collection);
        Collection<String> result = new ArrayList<>();
        for (String table : tables) {
            int index = table.lastIndexOf("_");
            String suffix = table.substring(index + 1);
            if (Integer.parseInt(suffix) <= Integer.parseInt(format)) {
                result.add(table);
            }
        }
        if (result.size() == 0){
            return collection;
        }
        return result;
    }

    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }

    @Override
    public String getType() {
        return "customer";
    }
}
